/**
 * 权限管理
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var util = require("util");

    var Permission = {
        init: function () {
            this._dataCallbacks = [];
            this._data = null;
            var $body = $('body');
            this._appCodes = getDefaultAppCode($body.attr('data-app-codes'));
            this._funcCodes = $body.attr('data-func-codes');

            this._pagePermission = $body.attr('data-permission');

            this._getData();
            function getDefaultAppCode(codes) {
                var arr = (codes || "").split(",");
                var tmp = {};
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i]) {
                        tmp[arr[i]] = true;
                    }
                }
                tmp["5003"] = true;//全民营销
                tmp["5008"] = true;//小蜜蜂
                tmp["5007"] = true;//渠道管家
                tmp["5004"] = true;//O2O应用
                tmp["5001"] = true;//微楼书
                tmp["0000"] = true;//系统管理
                arr = [];
                for (var n in tmp) {
                    arr.push(n);
                }
                return arr.join(",");
            }
        },
        _getData: function () {
            var self = this;
            var data = {
                functionCodes: this._funcCodes,
                token: util.getToken()
            };
            if (this._appCodes) {
                data['appCodes'] = this._appCodes;
            }
            util.myAjax({
                url: G_CONFIG.api_prefix + "identity/get-auth-actions-by-function-codes",
                type: "get",
                dataType: "json",
                data: data,
                cache: false,
                success: function (res) {
                    if (res['retCode'] == 0) {
                        self._data = res['data'];
                        self._update(self._data);
                        self._fire();
                    } else {
                        //self._showPermissionError();
                    }
                },
                error: function () {
                    self._showPermissionError();
                }
            })
        },
        _fire: function () {
            var callback;
            for (var i = 0; callback = this._dataCallbacks[i]; i++) {
                callback(this._data);
            }
        },
        /**
         * 获取权限数据
         * @param {function(Object)} callback
         */
        getData: function (callback) {
            this._dataCallbacks.push(callback);

            if (this._data) {
                this._fire();
            }
        },
        /**
         * 提示权限系统错误
         */
        _showPermissionError: function () {
            this.showTipAndForward('对不起，权限系统出现问题');
        },
        /**
         * 提示并跳转首页
         * @param {string} content
         */
        showTipAndForward: function (content) {
            require.async("dialog", function (dialog) {
                dialog({
                    title: '提示',
                    fixed: true,
                    content: content,
                    width: 350,
                    okValue: '返回首页',
                    cancelDisplay: false,
                    ok: function () {
                        location.href = '/';
                        return true;
                    },
                    cancel: function () {
                        location.href = '/';
                        return true;
                    }
                }).showModal();
            });
        },
        /**
         * 是否有权限访问页面
         * @param permissions
         * @returns {boolean}
         */
        hasPagePermission: function (permissions) {
            var pagePermission = this._pagePermission;

            if (typeof pagePermission === 'undefined' || pagePermission === 'all') {
                return true;
            }

            var item;
            for (var i = 0; item = permissions[i]; i++) {
                if (pagePermission == (item.funcCode + '-' + item.code)) {
                    return true;
                }
            }
            return false;
        },
        /**
         * @param {{functions:Array.<{appCode:string,funcCode:string,code:string}>,nav:Array.<string>}} data
         */
        _update: function (data) {
            var permissions = data.functions;
            var navPermissions = data.nav;

            var selBlockArr = [];
            var selInlineArr = [];
            var selInlineBlockArr = [];

            if (!this.hasPagePermission(permissions)) {
                util.showNoPagePermission();
                return;
            }

            var item;
            for (var i = 0; item = permissions[i]; i++) {
                var clsPart = item.funcCode + '-' + item.code;
                selBlockArr.push('.p-' + clsPart);
                selBlockArr.push('.p-' + clsPart + '-block');

                selInlineArr.push('.p-' + clsPart + '-inline');
                selInlineBlockArr.push('.p-' + clsPart + '-inline-block');
            }

            var navItem;
            for (var i = 0; navItem = navPermissions[i]; i++) {
                var clsPart = navItem;
                selBlockArr.push('.p-' + clsPart);
                selBlockArr.push('.p-' + clsPart + '-block');

                selInlineArr.push('.p-' + clsPart + '-inline');
                selInlineBlockArr.push('.p-' + clsPart + '-inline-block');
            }

            $('head').append(
                '<style type="text/css">' +
                '.permission{display:none !important;}' +
                selBlockArr.join(',') + '{display:block !important;}' +
                selInlineArr.join(',') + '{display:inline !important;}' +
                selInlineBlockArr.join(',') + '{display:inline-block !important;}' +
                '</style>'
            )
        }
    };

    Permission.init();

    return Permission;
});